package zasm.zasm.util;

import java.io.IOException;

public class LineReaderStack extends Stack<ILineReader> implements ILineReader {

	private static class EmptyLineReader implements ILineReader {

		public static final EmptyLineReader	INSTANCE	= new EmptyLineReader();

		private EmptyLineReader() {}

		@Override
		public String peekLine() {
			return null;
		}

		@Override
		public String readLine() {
			return null;
		}

		@Override
		public int getLineNumber() {
			return 0;
		}

		@Override
		public int getNextLineNumber() {
			return 1;
		}

		@Override
		public void close() {}

	}

	private ILineReader	top	= EmptyLineReader.INSTANCE;

	public LineReaderStack() {
		super();
	}

	@Override
	public void push(final ILineReader lineReader) {
		super.push(lineReader);
		top = lineReader;
	}

	@Override
	public ILineReader pop() {
		final ILineReader popped = super.pop();
		top = isEmpty() ? EmptyLineReader.INSTANCE : peek();
		return popped;
	}

	@Override
	public String peekLine() throws IOException {
		String line;
		for (line = top.peekLine(); (line == null) && !isEmpty(); pop()) {}
		return line;
	}

	@Override
	public String readLine() throws IOException {
		String line;
		for (line = top.readLine(); (line == null) && !isEmpty(); pop()) {}
		return line;
	}

	@Override
	public int getLineNumber() {
		return top.getLineNumber();
	}

	@Override
	public int getNextLineNumber() {
		return top.getNextLineNumber();
	}

	@Override
	public void close() throws IOException {
		while (!isEmpty()) {
			pop();
			top.close();
		}
	}

}
